package com.tfc.glassesfree3dplayer;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.opencv.android.OpenCVLoader;
import org.opencv.objdetect.CascadeClassifier;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_VIDEO_FILE = 1001;
    private static final int REQUEST_CODE_STORAGE_PERMISSION = 100;
    private static final int REQUEST_CODE_MANAGE_STORAGE = 101;
    public static CascadeClassifier classifierFace;
    public static CascadeClassifier classifierEye;
    public static String TAG = "3D_Player";
    public static String videoPath = null;
    public static Uri videoUri = null;
    public static long videoDuration = 0;  //视频时长
    public static String videoTimeString = null;   //视频时长字符串
    int chooseIndex = 0;
    String[] linkList = {
            "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear2/prog_index.m3u8",
            "https://v5-dy-o-detect.zjcdn.com/ec5c4cef1afd8987e37fa860d37a28f6/684b90c9/video/tos/cn/tos-cn-ve-15c001-alinc2/owFpsGToBAx4AoQgE7YDs9OBDMEfIUheAc0gQD/?a=1128&ch=0&cr=0&dr=0&cd=0%7C0%7C0%7C0&cv=1&br=1651&bt=1651&cs=0&ds=3&ft=tFF4488-oLsD12Nn5iUh-UxrXTc_gF_O51Y&mime_type=video_mp4&qs=0&rc=ZDpmZGQ3M2QzZjM0OjU3OUBpM242Nnc5cm42MzMzNGkzM0AvYTVeY2EzNl8xNF4uMF5iYSNhbC9rMmQ0aC9hLS1kLTBzcw%3D%3D&btag=80010e00090000&cquery=100y&dy_q=1749779112&feature_id=fea919893f650a8c49286568590446ef&l=20250613094512DB70CDCA0E6FF261A9E5",
            "http://vjs.zencdn.net/v/oceans.mp4",
            "https://media.w3.org/2010/05/sintel/trailer.mp4",
            "rtmp://ns8.indexforce.com/home/mystream",
            "rtmp://liteavapp.qcloud.com/live/liteavdemoplayerstreamid"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        //在开启了EdgeToEdge的情况下，防止内容与状态栏重叠
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        //初始化
        init();

        //创建组件对象
        Button openLocalVideoButton = findViewById(R.id.open_local_video_button);
        Button openWebVideoButton = findViewById(R.id.open_web_video_button);
        Button openDouyinVideoButton = findViewById(R.id.douyin_video_button);
        //监听组件
        openLocalVideoButton.setOnClickListener(v -> {
            //检查并获取权限
            if(checkAndRequestStoragePermissions()){
                // 打开视频文件选择器
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("video/*");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
                startActivityForResult(intent, REQUEST_VIDEO_FILE);
            }else{
                //未获取到权限，增加提示
                Toast.makeText(this, "请打开文件读取权限！", Toast.LENGTH_SHORT).show();
            }
        });
        openWebVideoButton.setOnClickListener(v -> {
            // 获取 ConnectivityManager
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            // 检查当前网络状态
            Network activeNetwork = connectivityManager.getActiveNetwork();
            boolean isConnected = false;
            if (activeNetwork != null) {
                NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork);
                isConnected = networkCapabilities != null && ( networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET));
            }
            // 网络状态判断
            if (isConnected) {
                //网络已连接，检查并获取权限
                if(checkAndRequestStoragePermissions()){
                    //创建一个警告对话框
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    chooseIndex = 0;
                    builder.setTitle("选择在线视频链接")
                            .setPositiveButton("确定", (dialog, which) -> {
                                videoPath = linkList[chooseIndex];
                                //获取到视频地址检查相机权限
                                if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                                    // 获取到相机权限，进入下一个Activity
                                    startActivity(new Intent(MainActivity.this, PlayOnlineActivity.class));
                                }else{
                                    Toast.makeText(MainActivity.this,"未获取到相机权限",Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setNegativeButton("取消", (dialog, which) -> Toast.makeText(MainActivity.this,"选择了取消",Toast.LENGTH_SHORT).show())
                            .setSingleChoiceItems(linkList, 0, (dialog, which) -> chooseIndex = which);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }else{
                    //未获取到权限，增加提示
                    Toast.makeText(this, "请打开文件读取权限！", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "网络未连接，请连接网络后重试", Toast.LENGTH_SHORT).show();
            }
        });

        openDouyinVideoButton.setOnClickListener(v -> {
            // 获取 ConnectivityManager
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            // 检查当前网络状态
            Network activeNetwork = connectivityManager.getActiveNetwork();
            boolean isConnected = false;
            if (activeNetwork != null) {
                NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork);
                isConnected = networkCapabilities != null && ( networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET));
            }
            // 网络状态判断
            if (isConnected) {
                startActivity(new Intent(MainActivity.this, DouyinVideo.class));
            } else {
                Toast.makeText(this, "网络未连接，请连接网络后重试", Toast.LENGTH_SHORT).show();
            }
        });
    }

    //初始化
    private void init() {
        //初始化OpenCV
        initOpenCV();
        //初始化人脸和人眼级联分类器
        initClassifierEye();
        initClassifierFace();
    }

    //初始化OpenCV
    public void initOpenCV() {
        if (OpenCVLoader.initLocal()) {
            Log.i(TAG, "OpenCV加载成功");
        } else {
            Log.e(TAG, "OpenCV加载失败");
            Toast.makeText(this, "OpenCV加载失败！", Toast.LENGTH_SHORT).show();
        }
    }

    //初始化人脸级联分类器
    public void initClassifierFace() {
        try {
            //读取存放在raw的文件
            InputStream is = getResources().openRawResource(R.raw.haarcascade_frontalface_alt2);
            File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
            File cascadeFile = new File(cascadeDir, "haarcascade_frontalface_alt2.xml");
            FileOutputStream os = new FileOutputStream(cascadeFile);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            is.close();
            os.close();
            classifierFace = new CascadeClassifier(cascadeFile.getAbsolutePath());
            Log.i(TAG, "人脸级联分类器初始化成功");
        } catch (IOException e) {
            Toast.makeText(this, "人脸级联分类器初始化失败！", Toast.LENGTH_SHORT).show();
            Log.e(TAG, Objects.requireNonNull(e.getMessage()));
        }
    }

    //初始化人眼级联分类器
    public void initClassifierEye() {
        try {
            //读取存放在raw的文件
            InputStream is = getResources().openRawResource(R.raw.haarcascade_eye_tree_eyeglasses);
            File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
            File cascadeFile = new File(cascadeDir, "haarcascade_eye_tree_eyeglasses.xml");
            FileOutputStream os = new FileOutputStream(cascadeFile);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            is.close();
            os.close();
            classifierEye = new CascadeClassifier(cascadeFile.getAbsolutePath());
            Log.i(TAG, "人眼级联分类器初始化成功");
        } catch (IOException e) {
            Toast.makeText(this, "人眼级联分类器初始化失败！", Toast.LENGTH_SHORT).show();
            Log.e(TAG, Objects.requireNonNull(e.getMessage()));
        }
    }

    //检测并请求权限
    private boolean checkAndRequestStoragePermissions() {
        //获取相机权限
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 100);
        }
        //获取存储权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11 (API 30)及以上版本
            if (!Environment.isExternalStorageManager()) {
                // 请求MANAGE_EXTERNAL_STORAGE权限
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_CODE_MANAGE_STORAGE);
            } else {
                // 已经有权限
                return true;
            }
        } else {
            // Android 10及以下版本
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_STORAGE_PERMISSION);
            } else {
                // 已经有权限
                return true;
            }
        }
        return false;
    }

    //处理文件选择器返回
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取到权限，处理文件
        if (requestCode == REQUEST_VIDEO_FILE && resultCode == RESULT_OK && data != null) {
            //获取文件Uri
            videoUri = data.getData();
            Log.i(TAG, "视频Uri路径：" + videoUri);
            // 获取文件真实路径
            videoPath = getRealPathFromUri(videoUri);
            Log.i(TAG, "视频真实路径：" + videoPath);
            //获取到视频真实路径，检查相机权限
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                //获取视频时长
                try {
                    MediaPlayer mediaPlayer = new MediaPlayer();
                    mediaPlayer.setDataSource(videoPath);
                    mediaPlayer.prepare();
                    videoDuration = mediaPlayer.getDuration();
                    mediaPlayer.release();
                    Log.i(TAG, String.valueOf(videoDuration));
                    //时间格式化
                    videoDuration = videoDuration/1000;
                    int hours = (int) (videoDuration / 3600); // 计算小时数
                    int remainder = (int) (videoDuration % 3600); // 计算剩余秒数
                    int minutes = remainder / 60; // 计算分钟数
                    int seconds = remainder % 60; // 计算剩余秒数
                    videoTimeString = String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds);
                    Log.i(TAG, "视频时长：" + videoTimeString);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                // 获取到相机权限，进入下一个Activity
                startActivity(new Intent(MainActivity.this, PlayerActivity.class));
            }else{
                Toast.makeText(MainActivity.this,"未获取到相机权限",Toast.LENGTH_SHORT).show();
            }
        }
    }

    //从uri获取文件真实路径
    private String getRealPathFromUri(Uri uri) {
        String filePath = null;
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是 Document URI
            String wholeID = DocumentsContract.getDocumentId(uri);

            // 分割 ID 和类型
            String id = wholeID.split(":")[1];
            String[] column = {MediaStore.Video.Media.DATA};

            // 查询真实路径
            String sel = MediaStore.Video.Media._ID + "=?";
            Cursor cursor = getContentResolver().query(
                    MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                    column, sel, new String[]{id}, null);

            if (cursor != null) {
                int columnIndex = cursor.getColumnIndex(column[0]);
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(columnIndex);
                }
                cursor.close();
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 普通 Content URI
            String[] projection = {MediaStore.Video.Media.DATA};
            try (Cursor cursor = getContentResolver().query(uri, projection, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                    filePath = cursor.getString(column_index);
                }
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // File URI
            filePath = uri.getPath();
        }
        return filePath;
    }
}